package com.qkl.xiatang.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qkl.xiatang.app.dto.BusinessDTO;
import com.qkl.xiatang.app.dto.PageOutDTO;
import com.qkl.xiatang.app.dto.log.JobLogInDTO;
import com.qkl.xiatang.app.dto.log.JobLogOutDTO;
import com.qkl.xiatang.app.dto.upload.*;
import com.qkl.xiatang.app.entity.feed.FeedAllocCheckEntity;
import com.qkl.xiatang.app.entity.feed.FeedAllocDetailEntity;
import com.qkl.xiatang.app.entity.pond.PondEntity;
import com.qkl.xiatang.app.entity.upload.UploadCommonFileEntity;
import com.qkl.xiatang.app.entity.upload.UploadFileEntity;
import com.qkl.xiatang.app.entity.user.AppUserInfo;
import com.qkl.xiatang.app.mapper.*;
import com.qkl.xiatang.app.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class UploadFileService {

    private static final String UPLOAD_URL = "/uploadApi/uploadFile";

    private static final String DOWNLOAD_URL = "/downloadApi/";

    @Autowired
    private ConfigService configService;

    @Autowired
    private UploadFileMapper uploadFileMapper;

    @Autowired
    private FeedAllocMapper feedAllocMapper;

    @Autowired
    private AppUserInfoMapper appUserInfoMapper;

    @Autowired
    private PondManagerMapper pondManagerMapper;

    @Autowired
    private FeedAllocCheckMapper feedAllocCheckMapper;

    @Autowired
    private UploadCommonFileMapper uploadCommonFileMapper;


    /**
     * 文件上传
     * @param fileDTO
     * @return
     */
    public BusinessDTO<Object> uploadFile(UploadFileDTO fileDTO){
        if(null == fileDTO){
            return BusinessDTO.failBusiness("请求方式有误，文件上传失败");
        }
        log.info("==uploadFile.getOriginalFilename={}",fileDTO.getOriginalFilename());
        String companyId = AppSessionUtils.getCompanyId();
        if(fileDTO.uploadTypeCheck()){
            return this.uploadFileCheck(companyId,fileDTO);
        }
        return BusinessDTO.failBusiness("不支持此文件上传业务");
    }
    /**
     * 上传,查料台视频
     * @param companyId
     * @param fileDTO
     * @return
     */
    private BusinessDTO<Object> uploadFileCheck(String companyId,UploadFileDTO fileDTO){
        String fileDirPath = FileUtils.uploadDirPath(companyId);
        String fileName = FileUtils.genFilePrefix() + "." + FileUtils.getFileSuffix(fileDTO.getOriginalFilename());
        String filePath = fileDirPath + fileName;
        log.info("===uploadFileCheck.filePath={}",filePath);
        Map<String,String> params = new HashMap<>();
        params.put("filePath",filePath);
        params.put("fileDirPath",fileDirPath);

        UploadHttpDTO httpDTO = new UploadHttpDTO();
        httpDTO.setFileName(fileName);
        httpDTO.setName(fileDTO.getName());
        httpDTO.setFileContent(fileDTO.getContent());
        httpDTO.setParams(params);

        String url = configService.uploadFileUrl() + UPLOAD_URL;
        HttpResponse<String>  response = HttpUtils.uploadFile(url,httpDTO);
        log.info("====uploadFile.response={}",response);
        String errMsg = "上传失败";
        if(response.isSuccess()){
            String jsonData = response.getData();
            if(StringUtils.isNotEmpty(jsonData)) {
                Result result = JSON.parseObject(jsonData, Result.class);
                if (result.resultSuccess()) {
                    return BusinessDTO.sucessBusiness(new HashMap<>(), "上传成功");
                }else {
                    errMsg = result.getMessage();
                }
            }
        }
        return BusinessDTO.failBusiness(errMsg);
    }

    public BusinessDTO<Object> uploadFileSubmit(UploadFileWebDTO webDTO){
        log.info("======uploadFileSubmit.webDTO={}",webDTO);
        if(webDTO.uploadTypeCheck()){
            return this.uploadFileCheckSubmit(webDTO);
        }
        return BusinessDTO.failBusiness("不支持此文件上传业务");
    }

    /**
     * 查料台视频提交上传
     * @param webDTO
     * @return
     */
    private BusinessDTO<Object> uploadFileCheckSubmit(UploadFileWebDTO webDTO){
        //String companyId = AppSessionUtils.getCompanyId();
        String ownerUserId = StringUtils.trimToEmpty(webDTO.getOwnerUserId());
        String fileSuffix = StringUtils.trimToEmpty(webDTO.getFileSuffix());
        String fileTime = StringUtils.trimToEmpty(webDTO.getFileTime());
        String taskId = StringUtils.trimToEmpty(webDTO.getTaskId());
        if(StringUtils.isAnyEmpty(ownerUserId,taskId)){
            return BusinessDTO.failBusiness(ErrorCodeUtils.PARAM_EMPTY,ErrorCodeUtils.PARAM_EMPTY_MSG);
        }
        FeedAllocCheckEntity task = feedAllocCheckMapper.selectById(taskId);
        //FeedAllocDetailEntity task = feedAllocMapper.selectById(taskId);
        if(null == task){
            return BusinessDTO.failBusiness("无此任务");
        }
        AppUserInfo  ownerUser = appUserInfoMapper.selectById(ownerUserId);
        if(null == ownerUser){
            return BusinessDTO.failBusiness("无拍摄者用户信息");
        }
        PondEntity pond = pondManagerMapper.selectById(task.getPondId());
        if(null == pond){
            return BusinessDTO.failBusiness("无此塘口");
        }
        String companyId = task.getCompanyId();
        String fileDirPath = FileUtils.uploadDirPath(companyId);
        String fileName = FileUtils.genFilePrefix() + "." + FileUtils.getFileSuffix(fileSuffix);
        String filePath = fileDirPath + fileName;
        log.info("===uploadFileCheckSubmit.filePath={}",filePath);

        String uploadId = AppUtils.genIdStr();
        String downloadUrl = configService.uploadFileUrl() + DOWNLOAD_URL + filePath;

        String memo = "查料台";
        QueryWrapper wrapper = new QueryWrapper<FeedAllocDetailEntity>().eq("company_id",companyId).eq("pond_id",task.getPondId()).eq("alloc_date",task.getAllocDate()).eq("serial_no",task.getSerialNo());
        List<FeedAllocDetailEntity> detailList = feedAllocMapper.selectList(wrapper);
        if(ObjectUtils.isNotEmpty(detailList)){
            Date feedTime = detailList.get(0).getFeedTime();
            Date checkTime = detailList.get(0).getCheckTime();
            if( null != feedTime && null != checkTime){
                int m = (int)((checkTime.getTime() - feedTime.getTime())/(1000 * 60));
                memo = memo + " 间隔" + m + "分钟";
            }
        }

        UploadFileEntity uploadFile = new UploadFileEntity();
        uploadFile.setId(uploadId);
        uploadFile.setCompanyId(task.getCompanyId());
        uploadFile.setFileTime(parseFileTime(fileTime));
        uploadFile.setUploadUserId(AppSessionUtils.getUserId());
        uploadFile.setUploadUserName(AppSessionUtils.getUserName());
        uploadFile.setMemo(memo);
        uploadFile.setTaskId(taskId);
        uploadFile.setTaskSerialNo(task.getSerialNo());
        uploadFile.setTaskSerialName(task.getSerialName());
        uploadFile.setType(UploadFileEntity.TYPE_CHECK);
        uploadFile.setTypeSub(task.getSerialNo());
        uploadFile.setOwnerUserId(ownerUserId);
        uploadFile.setOwnerUserName(ownerUser.getName());
        uploadFile.setPondName(pond.getName());
        uploadFile.setPondId(pond.getId());
        uploadFile.setPondSerialNo(pond.getSerialNo());
        uploadFile.setTaskDate(task.getAllocDate());
        uploadFile.setUploadFlag(1);
        uploadFile.setDownloadUrl(downloadUrl);
        uploadFile.setFilePath(filePath);
        uploadFileMapper.insert(uploadFile);
        return BusinessDTO.sucessBusiness(uploadResponse(fileDirPath,filePath,uploadId),"查料台视频提交上传");
    }

    /**
     * 共公文件上传提交
     * @param webDTO
     * @return
     */
    public BusinessDTO<Object> uploadCommonFileSubmit(UploadCommonFileWebDTO webDTO){
        String fileSuffix = StringUtils.trimToEmpty(webDTO.getFileSuffix());
        String memo = StringUtils.trimToEmpty(webDTO.getMemo());
        String userName = StringUtils.trimToEmpty(webDTO.getUserName());

        String fileDirPath = FileUtils.companyPath(null) + FileUtils.SEP;
        String fileName = FileUtils.genFilePrefix() + "." + FileUtils.getFileSuffix(fileSuffix);
        String filePath = fileDirPath + fileName;
        log.info("===uploadFileCheckSubmit.filePath={}",filePath);

        String uploadId = AppUtils.genIdStr();
        String downloadUrl = configService.uploadFileUrl() + DOWNLOAD_URL + filePath;

        UploadCommonFileEntity entity = new UploadCommonFileEntity();
        entity.setId(uploadId);
        entity.setMemo(memo);
        entity.setUploadDate(AppUtils.todayYyyyMMdd());
        entity.setType(webDTO.getType());
        entity.setTypeSub(webDTO.getTypeSub());
        entity.setTitle(webDTO.getTitle());
        entity.setTitleSub(webDTO.getTitleSub());
        entity.setCreateBy(userName);
        entity.setFilePath(filePath);
        entity.setDownloadUrl(downloadUrl);
        uploadCommonFileMapper.insert(entity);
        return BusinessDTO.sucessBusiness(uploadResponse(fileDirPath,filePath,uploadId),"共公文件上传提交");
    }

    /**
     * 共公文件删除
     * @param uploadId
     * @return
     */
    public BusinessDTO<Object> deleteCommonFile(String uploadId){
        UploadCommonFileEntity entity = uploadCommonFileMapper.selectById(uploadId);
        if(null == entity){
            return BusinessDTO.failBusiness("无此文件");
        }
        uploadCommonFileMapper.deleteById(uploadId);
        return BusinessDTO.sucessBusiness(uploadResponse("",entity.getFilePath(),uploadId),"共公文件上传提交");
    }


    /**
     * 视频日志
     * @param indto
     * @return
     */
    public BusinessDTO<JobLogOutDTO> queryVideoJobLog(JobLogInDTO indto){
        //List<JobLogTitleDTO> jobLogTitle = new ArrayList<>();
        indto.orderSort();
        log.info("=======queryVideoJobLog.indto={}",indto);
        String sign = CommonCryptoUtils.encryptEncodedUpload(AppSessionUtils.getUserName());
        indto.setSign(sign);
        Integer totalRow = uploadFileMapper.queryVideoJobLogListTotal(indto);
        totalRow = null == totalRow? 0:totalRow;
        JobLogOutDTO outDTO = new JobLogOutDTO();
        outDTO.settingPage(indto,totalRow);
        if(totalRow > 0){
            //List<JobLogVO> jobLogList = feedAllocMapper.queryZooJobLogList(indto);
            outDTO.setList(uploadFileMapper.queryVideoJobLogList(indto));
        }
        //outDTO.setJobLogTitle(jobLogTitle);
        outDTO.setJobLogTitle(new ArrayList<>());
        if(ObjectUtils.isEmpty(outDTO.getList())){
            outDTO.setList(new ArrayList());
        }
        return BusinessDTO.sucessBusiness(outDTO,"视频日志查询");
    }

    /**
     * 养殖视频查询
     * @param webDTO
     * @return
     */
    public BusinessDTO<PageOutDTO> queryBreedVideo(CommonQueryInDTO webDTO){
        webDTO.checkParam();
        webDTO.setTypeList(new ArrayList<>());
        webDTO.getTypeList().add(CommonQueryInDTO.TYPE_BREED);
        log.info("=======queryBreedVideo.webDTO={}",webDTO);
        String sign = CommonCryptoUtils.encryptEncodedUpload(AppSessionUtils.getUserName());
        webDTO.setSign(sign);

        Integer totalRow = uploadFileMapper.queryCommonFileListTotal(webDTO);
        totalRow = null == totalRow? 0:totalRow;
        PageOutDTO outDTO = new PageOutDTO();
        outDTO.settingPage(webDTO,totalRow);
        if(totalRow > 0){
            outDTO.setList(uploadFileMapper.queryCommonFileList(webDTO));
        }
        outDTO.setList(uploadFileMapper.queryCommonFileList(webDTO));
        //outDTO.setJobLogTitle(new ArrayList<>());
        if(ObjectUtils.isEmpty(outDTO.getList())){
            outDTO.setList(new ArrayList());
        }
        return BusinessDTO.sucessBusiness(outDTO,"养殖视频查询");
    }

    /**
     * 查料台过期视频目录
     * @return
     */
    public BusinessDTO<Object> queryExpireCheckDirectory(){
        List<String> directoryList = new ArrayList<>();
        String expireDaysString = configService.getConfigureValue("upload_file_expire_days");
        Integer expireDays = AppUtils.parseInt(expireDaysString);
        if(null != expireDays){
            List<QueryExpireFileVO> fileVOList = this.queryExpireUploadFile("",expireDays,1);
            if(ObjectUtils.isNotEmpty(fileVOList)){
                for(QueryExpireFileVO fileVO : fileVOList){
                    directoryList.add(fileVO.toDirectory());
                }
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("directoryList",directoryList);
        return BusinessDTO.sucessBusiness(map,"查料台过期视频目录");
    }

    /**
     * 过期文件
     * @param companyId
     * @param typeList
     * @param expireDays 过期天数
     * @return
     */
    private List<QueryExpireFileVO> queryExpireUploadFile(String companyId, int expireDays, List<Integer> typeList){
        Date taskDateStart = AppDateUtils.addDaysForToday(-(expireDays + 2));
        Date taskDateEnd = AppDateUtils.addDaysForToday(-expireDays);
        QueryExpireFileInDTO inDTO = new QueryExpireFileInDTO();
        inDTO.setCompanyId(companyId);
        inDTO.setTaskDateStart(taskDateStart);
        inDTO.setTaskDateEnd(taskDateEnd);
        inDTO.setTypeList(typeList);
        return uploadFileMapper.queryExpireUploadFile(inDTO);
    }
    private List<QueryExpireFileVO> queryExpireUploadFile(String companyId,int expireDays,Integer type){
        List<Integer> typeList = new ArrayList<>();
        typeList.add(type);
        return this.queryExpireUploadFile(companyId,expireDays,typeList);
    }

    private static Date parseFileTime(String fileTime){
        if(StringUtils.isNotEmpty(fileTime)){
            try {
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(fileTime);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

    private static Map<String,Object> uploadResponse(String fileDirPath,String filePath,String uploadId){
        Map<String,Object> map = new HashMap<>();
        map.put("fileDirPath",fileDirPath);
        map.put("filePath",filePath);
        map.put("uploadId",uploadId);
        return map;
    }

}
